var GameTools = {
    ajaxCookie: null,
    /**
     * 从本地储存中获取信息, 如果没有数据，添加默认数据value
     */
    getItemByLocalStorage(key, value) {
        let values = cc.sys.localStorage.getItem(key);
        if (values === undefined || values === null || values === '') {
            cc.sys.localStorage.setItem(key, value);
            return value;
        }
        if (typeof value === 'boolean') {
            if (typeof values === 'boolean') {
                return values;
            }
            return "true" == values;
        } else if (typeof value === 'number') {
            return Number(values);
        }
        return values;
    },

    /**
     * 本地存储存储信息
     */
    setItemByLocalStorage(key, value) {
        cc.sys.localStorage.setItem(key, value);
    },

    /**
     * 提交分数
     */
    submitScore(score, MAIN_MENU_NUM) {
        if (CC_WECHATGAME) {
            wx.postMessage({
                messageType: 1, // 提交分数
                score: score,
                MAIN_MENU_NUM: MAIN_MENU_NUM,
            });   
        }
    },

    /**
     * 生成实例
     */
    getInstanceFromBox(box) {
        var random = parseInt(Math.random()*box.length);
        if (box[random].pool.size() > 0) {
            return box[random].pool.get(this);
        }
        return cc.instantiate(box[random].pref);
    },

    /**
     * 50%概率
     */
    percent50() {
        return parseInt(Math.random()*2) == 0;
    },

    ajax(url, data, success, error, type="POST") {
        let _self = this;
        wx.request({
            url: "https://wg.iwckj.com" + url,
            data: data,
            method: type,
            header: {
                'content-type':'application/x-www-form-urlencoded',
                'Cookie': _self.ajaxCookie
            },
            success: function (res) {
                if (res.data.data && res.data.data.sessionId) {
                    _self.ajaxCookie = 'SESSION=' + res.data.data.sessionId;
                }
                if(res.code == '1001') {
                    console.log("未登录");
                } else{
                    success && success(res.data);
                }
            },
            fail: function (res) {
                error && error();
            }
        });
    },
};

export default GameTools;